package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Sum implements Callable<Long> {
    private int from;
    private int to;

    public Sum() {
    }

    public Sum(int from, int to) {
        this.from = from;
        this.to = to;
    }

    @Override
    public Long call() throws Exception {
        long res = 0L;
        for (int i = from; i < to; i++) {
            res+=i;
        }
        return res;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Long res = 0L;
        //单线程从1加到一亿的时间
        System.out.println("单线程从1加到一亿的时间");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            res+=i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        System.out.println(res);

        System.out.println("多线程从1加到一亿的时间");
        //多线程从1加到一亿的时间
        res = 0L;
        FutureTask[] futureTasks =new FutureTask[10];
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            FutureTask<Long> futureTask = new FutureTask<Long>(new Sum(i*10000000,(i+1)*10000000));
            new Thread(futureTask).start();
            futureTasks[i] = futureTask;
        }
        for (int i = 0; i < futureTasks.length; i++) {
            long o = (Long)futureTasks[i].get();
            res+=o;
        }


        long end2 = System.currentTimeMillis();
        System.out.println(end2-start2);
        System.out.println(res);



    }
}
